import { NameSpace } from 'utils';
import exceed from 'utils/apimap';

const { pathResource, codeReviewDetail } = window.FORCE;
const ns = NameSpace('PROJECT_MR_LOG');

export const UPDATE_DATA = ns('UPDATE_DATA');
export const RESET_LOG_DATA = ns('RESET_LOG_DATA');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function getLogs(page) {
  return (dispatch, getState) => {
    const state = getState().project.projectMergeRequestDetail.commitsReducer;
    const { summaryLogs } = state;
    exceed
      .fetch({
        api: 'project.mr.commits',
        params: {
          projectId: pathResource.id,
          mrId: codeReviewDetail.id,
        },
        data: {
          show_signature: true,
          page,
        },
      })
      .then((result) => {
        const curSummaryLogs = [...summaryLogs, ...result.slice(1)];
        updateData({
          summaryLogs: curSummaryLogs,
          total: result[0].amount || 0,
          summaryLogsLoaded: true,
          currentPage: page,
        })(dispatch);
      })
      .fail((err) => {
        console.error(err);
      });
  };
}

export function resetLogs() {
  return (dispatch) => {
    dispatch({
      type: RESET_LOG_DATA,
    });
  };
}
